/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-08-28
*/
package com.rzico.market.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.market.entity.Invoice;
import com.rzico.market.model.InvoiceVo;
import com.rzico.market.service.InvoiceService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import com.rzico.util.StringUtils;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;

/**
 * 开票商品信息控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-08-28
 */
@Api(description = "开票商品信息接口")
@RestController
@RequestMapping("/admin/invoice")
public class InvoiceController extends BaseController {

    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private EnterpriseService enterpriseService;

    /**
     * 分页查询开票商品信息
     *
     * @return
    */
    @ApiOperation("分页查询开票商品信息")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderSn", value = "订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "productName", value = "商品名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态", dataType = "String", paramType = "query")
    })
    public CommResult<Invoice> list(Date startDate, Date endDate, Pageable pageable, String orderSn, String productName, String state) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
           params.put("startDate", startDate);
        }
        if (endDate!=null){
           params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }

        if (StringUtils.isNotEmpty(orderSn)) {
            params.put("orderSn", orderSn);
        }
        if (StringUtils.isNotEmpty(productName)) {
            params.put("productName", productName);
        }
        if (StringUtils.isNotEmpty(state)) {
            params.put("state", state);
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Invoice> list = invoiceService.selectList(params);
        PageResult<Invoice> pageResult = new PageResult<Invoice>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条开票商品信息
     *
     * @return
    */
    @ApiOperation("查询单条开票商品信息")
    @GetMapping("/find/{id}")
    public CommResult<Invoice> find(@PathVariable String id) {
        Invoice result = invoiceService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("invoice",result);
        return CommResult.success(data);

    }

    /**
     * 保存开票商品信息
     *
     * @param invoice
     * @return
     */
    @ApiOperation("保存开票商品信息")
    @PostMapping("/save")
    public CommResult<Invoice> save(@RequestBody Invoice invoice) {
        int affectCount = invoiceService.insert(invoice);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        Invoice result = invoiceService.findById(invoice.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除开票商品信息
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除开票商品信息", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除开票商品信息,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Invoice> del(@PathVariable String ids) {

        invoiceService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新开票商品信息
     *
     * @param invoice
     * @return
     */
    @Log(desc = "更新开票商品信息", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新开票商品信息")
    @PostMapping("/update")
    public CommResult<Invoice> update(@RequestBody Invoice invoice) {
        Enterprise enterprise = enterpriseService.getCurrent();
        if (null == enterprise) {
            return CommResult.error("没有开通企业");
        }

        Invoice dataInvoice = invoiceService.findById(invoice.getId());
        //开票数量不可比商品数量多
        if (0 < invoice.getInInvoiceQuantity().compareTo(dataInvoice.getProductQuantity())) {
            return CommResult.error("商品开票数量大于商品数量，请修改");
        } else if (0 == invoice.getInInvoiceQuantity().compareTo(dataInvoice.getProductQuantity())) {
            invoice.setState(true);
        } else if (0 > invoice.getInInvoiceQuantity().compareTo(dataInvoice.getProductQuantity())) {
            invoice.setState(false);
        }
        int affectCount = invoiceService.updateByPrimaryKeySelective(invoice);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Invoice result = invoiceService.findById(invoice.getId());
        return CommResult.success(result);
    }

    /**
     * 分页查询开票商品信息
     *
     * @return
     */
    @ApiOperation("分页查询开票商品信息")
    @GetMapping("/selectInvoiceInfoList")
    @ApiImplicitParams({@ApiImplicitParam(name = "startCompleteDate", value = "开始完成时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endCompleteDate", value = "结束完成时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "companyId", value = "公司Id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "supplierId", value = "供应商Id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "orderSn", value = "订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "productName", value = "商品名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "batchNum", value = "卡批次号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "invoiceState", value = "进项状态", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "invoiceItemState", value = "出项状态", dataType = "String", paramType = "query")
    })
    public CommResult<InvoiceVo> selectInvoiceInfoList(Pageable pageable, String startCompleteDate, String endCompleteDate, Long companyId, Long supplierId, String orderSn, String productName, String batchNum, String invoiceState, String invoiceItemState) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);

        if (null != startCompleteDate) {
            params.put("startCompleteDate", startCompleteDate);
        }
        if (null != endCompleteDate) {
            params.put("endCompleteDate", endCompleteDate);
        }
        if (null != companyId) {
            params.put("companyId", companyId);
        }
        if (null != supplierId) {
            params.put("supplierId", supplierId);
        }
        if (StringUtils.isNotEmpty(orderSn)) {
            params.put("orderSn", orderSn);
        }
        if (StringUtils.isNotEmpty(productName)) {
            params.put("productName", productName);
        }
        if (StringUtils.isNotEmpty(batchNum)) {
            params.put("batchNum", batchNum);
        }
        if (StringUtils.isNotEmpty(invoiceState)) {
            params.put("invoiceState", invoiceState);
        }
        if (StringUtils.isNotEmpty(invoiceItemState)) {
            params.put("invoiceItemState", invoiceItemState);
        }
        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<InvoiceVo> list = invoiceService.selectInvoiceInfoList(params);
        PageResult<InvoiceVo> pageResult = new PageResult<InvoiceVo>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

}
